package com.banciyuan.bcywebview.biz.main.mineinfo;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SpaceApi;
import com.banciyuan.bcywebview.base.fragment.BasePullLoadFragment;
import com.banciyuan.bcywebview.base.helper.FlagUtils;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.view.imageview.CircleImageView;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshScrollView;
import com.banciyuan.bcywebview.base.view.tag.TagView;
import com.banciyuan.bcywebview.biz.ask.AskActivity;
import com.banciyuan.bcywebview.biz.follow.FollowingActivity;
import com.banciyuan.bcywebview.biz.goods.shoppingcart.ShoppingCartHelper;
import com.banciyuan.bcywebview.biz.login.LoginActivity;
import com.banciyuan.bcywebview.biz.main.mineinfo.drafts.DraftsActivity;
import com.banciyuan.bcywebview.biz.main.mineinfo.message.MessageActivity;
import com.banciyuan.bcywebview.biz.main.mineinfo.mywork.MyWorkManagerActivity;
import com.banciyuan.bcywebview.biz.main.mineinfo.reward.MyRewardActivity;
import com.banciyuan.bcywebview.biz.main.mineinfo.zan.GetZanActivity;
import com.banciyuan.bcywebview.biz.pc.zone.smooth.SmoothPersonActivity;
import com.banciyuan.bcywebview.biz.privatemessage.PrivateMessageListActivity;
import com.banciyuan.bcywebview.biz.setting.SettingActivity;
import com.banciyuan.bcywebview.biz.web.WebActivity;
import com.banciyuan.bcywebview.biz.zanlist.ZanListActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.CommonApiUtils;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.DetailGoods;
import de.greenrobot.daoexample.model.MineInfo;
import de.greenrobot.daoexample.model.NotificationData;
import de.greenrobot.daoexample.model.Role;
import de.greenrobot.daoexample.model.TagDetail;

/**
 * Created by hy on 2015/4/22.
 */
public class MineInfoFragment2 extends BasePullLoadFragment implements View.OnClickListener {

    public static final int TAG = 4;
    private final int FROM_MINEINFO = 20;
    private final int TO_PRIVATEMESSAGE = 21;

    private PullToRefreshScrollView scrollView;

    private View mProgressbarView;
    private MineInfo mineInfo;
    private ProgressbarHelper mProgressbarHelper;
    private RelativeLayout rl_zan;
    private RelativeLayout rl_work;
    private RelativeLayout rl_setting;
    private RelativeLayout rl_store;
    private TextView zan_new;
    private TextView fans_num;
    private TextView focus_num;
    private TextView fans_add;
    private TextView gouda_add;
    private TextView name_tv;
    private TextView getzan_num;
    private TextView achievement;
    private CircleImageView head_img;
    private ImageView gender_img;
    private ImageView vip_img;
    private TagView ll_roles;
    private TextView tvDraftsCount;
    private View viewMessageRed;
    private View viewPrivateMessageRed;
    private View buy_car_num;
    private View login;
    private View addFriend;

    private RequestQueue mQueue;
    private ImageLoader imageLoader;
    private String uid;

    private final int max_limit = 1000000;
    private final int max_unit = 10000;

    private boolean is_init;


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootview = View.inflate(getActivity(), R.layout.fragment_mine_new, null);
        initArgs();
        initProgressbar(rootview);
        initUi(rootview);
        initAction();
        initData();
        readMessage();
        return rootview;
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(getActivity());
        imageLoader = ImageLoader.getInstance();
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
                readMessage();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        scrollView = (PullToRefreshScrollView) rootview.findViewById(R.id.scrollview);
        rl_zan = (RelativeLayout) rootview.findViewById(R.id.rl_zan);
        rl_work = (RelativeLayout) rootview.findViewById(R.id.rl_work);
        rl_setting = (RelativeLayout) rootview.findViewById(R.id.rl_seting);
        fans_num = (TextView) rootview.findViewById(R.id.fans_num);
        focus_num = (TextView) rootview.findViewById(R.id.focus_num);
        fans_add = (TextView) rootview.findViewById(R.id.fans_add);
        gouda_add = (TextView) rootview.findViewById(R.id.gouda_add);
        name_tv = (TextView) rootview.findViewById(R.id.tv_name);
        head_img = (CircleImageView) rootview.findViewById(R.id.civ_touxiang);
        gender_img = (ImageView) rootview.findViewById(R.id.iv_gender);
        ll_roles = (TagView) rootview.findViewById(R.id.roles_container);
        tvDraftsCount = (TextView) rootview.findViewById(R.id.tv_drafts_count);
        viewMessageRed = rootview.findViewById(R.id.view_message_red);
        vip_img = (ImageView) rootview.findViewById(R.id.vip_logo);
        achievement = (TextView) rootview.findViewById(R.id.achievement_info);
        viewPrivateMessageRed = rootview.findViewById(R.id.view_privatemessage_red);
        buy_car_num = rootview.findViewById(R.id.buy_car_num);
        rl_store = (RelativeLayout) rootview.findViewById(R.id.store_line);
        getzan_num = (TextView) rootview.findViewById(R.id.getzan_num);
        zan_new = (TextView) rootview.findViewById(R.id.zan_new);
        login = rootview.findViewById(R.id.view_login);
        addFriend = rootview.findViewById(R.id.view_add_friends);
        if (SPHelper.getBoolean(getActivity(), SPConstant.FIRST_SHOW_ZAN, false)) {
            zan_new.setVisibility(View.GONE);
        } else {
            zan_new.setVisibility(View.VISIBLE);
        }
        checkNoticeView();
        rootview.findViewById(R.id.rl_focus).setOnClickListener(this);
        rootview.findViewById(R.id.rl_fans).setOnClickListener(this);
        rootview.findViewById(R.id.rl_gouda).setOnClickListener(this);
        rootview.findViewById(R.id.rl_myinfo).setOnClickListener(this);
        rootview.findViewById(R.id.rl_drafts).setOnClickListener(this);
        rootview.findViewById(R.id.rl_message).setOnClickListener(this);
        rootview.findViewById(R.id.rl_reward).setOnClickListener(this);
        rootview.findViewById(R.id.rl_privatemessage).setOnClickListener(this);
        rootview.findViewById(R.id.rl_cpgame).setOnClickListener(this);
        rootview.findViewById(R.id.rl_zannum).setOnClickListener(this);
        rootview.findViewById(R.id.rl_circle).setOnClickListener(this);
        addFriend.setOnClickListener(this);

        if (!TextUtils.isEmpty(UserDataHelper.getInstance(getActivity()).getToken())) {
            addFriend.setVisibility(View.VISIBLE);
            login.setVisibility(View.GONE);
        } else {
            addFriend.setVisibility(View.GONE);
            login.setVisibility(View.VISIBLE);
        }
    }

    private void checkNoticeView() {
        if (SPHelper.getBoolean(getActivity(), SPConstant.ACHIEVEREAD, true)) {
            SPHelper.putBoolean(getActivity(), SPConstant.ACHIEVEREAD, false);
            achievement.setVisibility(View.VISIBLE);
        } else {
            achievement.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    protected void initAction() {
        rl_zan.setOnClickListener(this);
        rl_work.setOnClickListener(this);
        rl_setting.setOnClickListener(this);
        rl_store.setOnClickListener(this);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoUtil.gotoAct(getActivity(), LoginActivity.class);
            }
        });

        scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                readMessage();
                initData();
            }
        });
    }

    private void readMessage() {
        if (!TextUtils.isEmpty(UserDataHelper.getInstance(getActivity()).getToken())) {
            CommonApiUtils.getMessageData(getActivity(), mQueue, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                            String data = new JSONObject(response).getString(HttpUtils.UPLOAD_DATA);
                            Gson gson = new Gson();
                            NotificationData notification = gson.fromJson(data, NotificationData.class);
                            BaseObserver.getInstance().notifyWatchers(BaseObserver.MESSAGE_EVENT, notification);
                            processMessage();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });
        }
    }

    private void processMessage() {
        processUserFollow();
        processUnAskData();
        processMessageRedCircle();
    }

    private void processUserFollow() {
        int userFollow = FlagUtils.newFansNum;
        if (userFollow > 0) {
            if (userFollow >= 100) {
                fans_add.setText("99+");
            } else {
                fans_add.setText("+" + userFollow);
            }
            fans_add.setVisibility(View.VISIBLE);
        } else {
            fans_add.setVisibility(View.GONE);
        }
    }

    private void processUnAskData() {
        int unasked = FlagUtils.newAskNum;
        if (unasked > 0) {
            if (unasked >= 99) {
                gouda_add.setText("99");
            } else {
                gouda_add.setText(String.valueOf(unasked));
            }
            gouda_add.setVisibility(View.VISIBLE);
        } else {
            gouda_add.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        if (!TextUtils.isEmpty(UserDataHelper.getInstance(getActivity()).getToken())) {
            List<BcyPair> paramsList = new ArrayList<>();
            paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
            String url = HttpUtils.BASE_URL + SpaceApi.getMe();
            Response.Listener succ = new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    try {
                        JSONObject result = new JSONObject(s);
                        if (StatusCodeUtils.dealStatusCode(s, getActivity())) {
                            JSONObject jsonObject = result.getJSONObject(HttpUtils.UPLOAD_DATA);
                            Gson gson = new Gson();
                            mineInfo = gson.fromJson(jsonObject.toString(), MineInfo.class);
                            processData();
                            is_init = true;
                        } else {
                            int status = result.getInt(HttpUtils.UPLOAD_STATUS);
                            if (status == 100) {
                                UserDataHelper.Logout(getActivity(), new UserDataHelper.ClearAliasCallBack() {
                                    @Override
                                    public void doclear() {
                                        gotoUtil.gotoAct(getActivity(), LoginActivity.class);
                                    }
                                });
                            }
                            is_init = true;
                            scrollView.onRefreshComplete();
                            mProgressbarHelper.onSuccess();
                        }
                    } catch (Exception e) {
                        is_init = true;
                        scrollView.onRefreshComplete();
                        mProgressbarHelper.onFailed();
                    }
                }
            };

            Response.ErrorListener error = new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    is_init = true;
                    scrollView.onRefreshComplete();
                    mProgressbarHelper.onFailed();
                }
            };
            HashMap<String, String> params = HttpUtils.getData(paramsList);
            OnErrorProxy errorProxy = new OnErrorProxy(error, succ, url, getActivity(), params);
            StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, errorProxy);
            mQueue.add(stringRequest);
        } else {
            renderNotLogin();
        }
    }

    private void renderNotLogin() {
        mProgressbarHelper.onCustom();
        LinearLayout linearLayout = mProgressbarHelper.getCustom();
        linearLayout.removeAllViews();
        View notLogin = View.inflate(getActivity(), R.layout.mine_info_not_login, null);
        notLogin.findViewById(R.id.login_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoUtil.gotoAct(getActivity(), LoginActivity.class);
            }
        });
        linearLayout.addView(notLogin);
    }

    private void processData() {
        if (mineInfo == null) return;
        uid = mineInfo.getUid();
        if (mineInfo.isValue_user()) {
            vip_img.setVisibility(View.VISIBLE);
        } else {
            vip_img.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(mineInfo.getAvatar()))
            imageLoader.displayImage(mineInfo.getAvatar(), head_img, ImageOptions.optionHead);
        if (!TextUtils.isEmpty(mineInfo.getUname()))
            name_tv.setText(mineInfo.getUname());
        if (mineInfo.getSex().equals("1")) {
            gender_img.setImageResource(R.drawable.profile_boy);
        } else {
            gender_img.setImageResource(R.drawable.gender_girl);
        }
        if (!TextUtils.isEmpty(mineInfo.getFollowing())) {
            if (Integer.parseInt(mineInfo.getFollowing()) > max_limit) {
                focus_num.setText(Integer.parseInt(mineInfo.getFollowing()) / max_unit + "w+");
            } else {
                focus_num.setText(mineInfo.getFollowing());
            }
        }
        if (!TextUtils.isEmpty(mineInfo.getFollower())) {
            if (Integer.parseInt(mineInfo.getFollower()) > max_limit) {
                fans_num.setText(Integer.parseInt(mineInfo.getFollower()) / max_unit + "w+");
            } else {
                fans_num.setText(mineInfo.getFollower());
            }
        }

        if (!mineInfo.getRoles().isEmpty()) {
            ll_roles.setVisibility(View.VISIBLE);
            List<TagDetail> tagDetails = new ArrayList<>();
            for (Role role : mineInfo.getRoles()) {
                TagDetail tagDetail = new TagDetail();
                tagDetail.setTag_name(role.getType_name());
                tagDetails.add(tagDetail);
            }
            ll_roles.setTlist(tagDetails);
        } else {
            ll_roles.setVisibility(View.GONE);
        }
        getzan_num.setText(String.valueOf(mineInfo.getDing_count()));
        processDraftsCount();
        readCar();
        scrollView.onRefreshComplete();
        mProgressbarHelper.onSuccess();
    }

    private void readCar() {
        List<DetailGoods> dlist = ShoppingCartHelper.getShoppingItems(getActivity());
        if (dlist.isEmpty()) {
            buy_car_num.setVisibility(View.GONE);
        } else {
            buy_car_num.setVisibility(View.VISIBLE);
        }
    }

    private void processMessageRedCircle() {
        if (FlagUtils.ifNotifyUpdate || FlagUtils.ifRemindUpdate || FlagUtils.ifSerializeUpdate || FlagUtils.ifAnnounce || FlagUtils.ifGroupUpdate) {
            viewMessageRed.setVisibility(View.VISIBLE);
        } else {
            viewMessageRed.setVisibility(View.GONE);
        }
        if (FlagUtils.ifMessage) {
            viewPrivateMessageRed.setVisibility(View.VISIBLE);
        } else {
            viewPrivateMessageRed.setVisibility(View.GONE);
        }
    }

    private void processDraftsCount() {
        String novelCount = SPHelper.getString(getActivity(), SPConstant.SPNAME_NOVELDRAFTS + UserDataHelper.getInstance(getActivity()).getUid(), SPConstant.NOVEL_COUNT, "0");
        if ("0".equals(novelCount)) {
            tvDraftsCount.setVisibility(View.INVISIBLE);
        } else {
            tvDraftsCount.setVisibility(View.VISIBLE);
            tvDraftsCount.setText(novelCount);
        }
    }

    @Override
    public void onClick(View view) {
        if (null == mineInfo || TextUtils.isEmpty(uid))
            return;
        Intent intent;
        switch (view.getId()) {
            case R.id.rl_myinfo:
                intent = new Intent(getActivity(), SmoothPersonActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, uid);
                intent.putExtra(gotoUtil.NEEDLOGOUT, true);
                getActivity().startActivityForResult(intent, FROM_MINEINFO);
                break;
            case R.id.rl_gouda:
                intent = new Intent(getActivity(), AskActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, uid);
                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, mineInfo.getUname());
                getActivity().startActivityForResult(intent, FROM_MINEINFO);
                break;
            case R.id.rl_focus:
                intent = new Intent(getActivity(), FollowingActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, uid);
                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, "following");
                intent.putExtra(gotoUtil.INTENT_VALUE_THREE, getString(R.string.choosefriend));
                getActivity().startActivityForResult(intent, FROM_MINEINFO);
                break;
            case R.id.rl_fans:
                intent = new Intent(getActivity(), FollowingActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, uid);
                intent.putExtra(gotoUtil.INTENT_VALUE_TWO, "follower");
                intent.putExtra(gotoUtil.INTENT_VALUE_THREE, getString(R.string.my_fans));
                getActivity().startActivityForResult(intent, FROM_MINEINFO);
                break;
            case R.id.rl_zan:
                intent = new Intent(getActivity(), ZanListActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, uid);
                getActivity().startActivityForResult(intent, FROM_MINEINFO);
                break;
            case R.id.rl_seting:
                intent = new Intent(getActivity(), SettingActivity.class);
                getActivity().startActivityForResult(intent, FROM_MINEINFO);
                break;
            case R.id.rl_work:
                intent = new Intent(getActivity(), MyWorkManagerActivity.class);
                getActivity().startActivityForResult(intent, FROM_MINEINFO);
                achievement.setVisibility(View.INVISIBLE);
                break;
            case R.id.rl_drafts:
                intent = new Intent(getActivity(), DraftsActivity.class);
                getActivity().startActivityForResult(intent, FROM_MINEINFO);
                break;
            case R.id.rl_message:
                intent = new Intent(getActivity(), MessageActivity.class);
                getActivity().startActivityForResult(intent, FROM_MINEINFO);
                break;
            case R.id.rl_reward:
                intent = new Intent(getActivity(), MyRewardActivity.class);
                getActivity().startActivityForResult(intent, FROM_MINEINFO);
                break;
            case R.id.view_add_friends:
                intent = new Intent(getActivity(), AddFriendsActivity.class);
                getActivity().startActivityForResult(intent, FROM_MINEINFO);
                break;
            case R.id.rl_privatemessage:
                intent = new Intent(getActivity(), PrivateMessageListActivity.class);
                getActivity().startActivityForResult(intent, TO_PRIVATEMESSAGE);
                break;
            case R.id.rl_cpgame:
                intent = new Intent(getActivity(), WebActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, getString(R.string.cp_game_url));
                startActivity(intent);
                break;
            case R.id.rl_circle:
                intent = new Intent(getActivity(), MyMarkActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_zannum:
                if (mineInfo != null) {
                    zan_new.setVisibility(View.GONE);
                    SPHelper.putBoolean(getActivity(), SPConstant.FIRST_SHOW_ZAN, true);
                    intent = new Intent(getActivity(), GetZanActivity.class);
                    intent.putExtra("count", mineInfo.getDing_count());
                    intent.putExtra("rank", mineInfo.getDing_rank());
                    getActivity().startActivityForResult(intent, FROM_MINEINFO);
                }
                break;
        }
    }

    @Override
    public void selfUpdateData() {
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.getRefreshableView().smoothScrollTo(0, 0);
                scrollView.setRefreshing();
            }
        });
    }

    public void renderUi() {
        if (FlagUtils.ifMimeUpdate && is_init) {
            FlagUtils.ifMimeUpdate = false;
            processMessage();
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FROM_MINEINFO) {
            processMessage();
        }
        if (requestCode == TO_PRIVATEMESSAGE) {
            if (data != null) {
                FlagUtils.ifMessage = !data.getBooleanExtra("allclear", false);
                processMessage();
            }
        }

    }
}
